package com.example.hello.controller;

import com.example.hello.pojo.Res;
import com.example.hello.service.InteractionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/interaction")
public class InteractionController {

    @Autowired
    private InteractionService interactionService;

    /**
     * PUT /interaction/favorite?userId=xxx&bookId=yyy
     * 用户点击“收藏”按钮：
     *   - 如果记录不存在，则插入一条新数据(rating=0, isFavorite=true, borrowCount=0)
     *   - 如果记录已存在，则更新 isFavorite=true
     */
    @PutMapping("/favorite")
    public Res markFavorite(@RequestParam Integer userId, @RequestParam Integer bookId) {
        try {
            interactionService.markFavorite(userId, bookId);
            return Res.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Res.error("收藏失败: " + e.getMessage());
        }
    }

    @PutMapping("/cancleFavorite")
    public Res cancleFavorite(@RequestParam Integer userId, @RequestParam Integer bookId) {
        try {
            interactionService.cancleFavorite(userId, bookId);
            return Res.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Res.error("收藏失败: " + e.getMessage());
        }
    }

    /**
     * PUT /interaction/rating?userId=xxx&bookId=yyy&rating=z
     *
     * 根据 userId 和 bookId 更新用户对图书的评分：
     * - 如果记录不存在，则插入新记录，rating为传入参数，isFavorite=false, borrowCount=0；
     * - 如果记录已存在，则更新记录中的 rating 为传入参数。
     *
     * @param userId 用户 ID
     * @param bookId 图书 ID
     * @param rating 新的评分值
     * @return 统一返回结果 Res
     */
    @PutMapping("/rating")
    public Res updateRating(
            @RequestParam Integer userId,
            @RequestParam Integer bookId,
            @RequestParam double rating) {
        try {
            interactionService.updateOrInsertRating(userId, bookId, rating);
            return Res.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Res.error("更新评分失败: " + e.getMessage());
        }
    }

    /**
     * PUT /interaction/borrow?userId=xxx&bookId=yyy
     * 用户点击“借阅”按钮的接口：
     * - 如果记录不存在，则插入新记录（rating=0, isFavorite=false, borrowCount=1）；
     * - 如果记录存在，则将 borrowCount 增加1。
     */
    @PutMapping("/borrow")
    public Res borrowBook(@RequestParam Integer userId, @RequestParam Integer bookId) {
        try {
            interactionService.borrowBook(userId, bookId);
            return Res.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Res.error("借阅操作失败: " + e.getMessage());
        }
    }
}